package user

import (
	"fmt"
	"jihe.common/protos/user_server/proto"
	"strings"
)

func (s *Model) Create(in *proto.UserUser) (err error) {
	intoMap := make(map[string]interface{})
	intoMap["uid"] = in.Uid
	intoMap["role"] = in.Role
	intoMap["discount"] = in.Discount
	fields, vals, args := make([]string, 0), make([]interface{}, 0), make([]string, 0)
	valNum := 0
	for field, val := range intoMap {
		fields = append(fields, field)
		vals = append(vals, val)
		valNum++
		args = append(args, fmt.Sprintf("$%d", valNum))
	}
	sqlStr := fmt.Sprintf("INSERT INTO %s ("+strings.Join(fields, ",")+")VALUES("+strings.Join(args, ",")+")", s.Name)
	_, err = s.Db.Exec(sqlStr, vals...)
	if err != nil {
		return
	}
	return
}

func (s *Tx) Create(in *proto.UserUser) (err error) {
	intoMap := make(map[string]interface{})
	intoMap["uid"] = in.Uid
	intoMap["role"] = in.Role
	intoMap["discount"] = in.Discount
	fields, vals, args := make([]string, 0), make([]interface{}, 0), make([]string, 0)
	valNum := 0
	for field, val := range intoMap {
		fields = append(fields, field)
		vals = append(vals, val)
		valNum++
		args = append(args, fmt.Sprintf("$%d", valNum))
	}
	sqlStr := fmt.Sprintf("INSERT INTO %s ("+strings.Join(fields, ",")+")VALUES("+strings.Join(args, ",")+")", s.Name)
	_, err = s.Db.Exec(sqlStr, vals...)
	if err != nil {
		return
	}
	return
}

func (s *Model) UpdateByUid(in *proto.UserUser) (err error) {
	intoMap := make(map[string]interface{})
	if in.Discount != 0 {
		intoMap["discount"] = in.Discount
	}
	if in.PlatformDiscount != 0 {
		intoMap["platform_discount"] = in.PlatformDiscount
	}
	fields, vals := make([]string, 0), make([]interface{}, 0)
	valNum := 0
	for field, val := range intoMap {
		valNum++
		fields = append(fields, fmt.Sprintf("%s=$%d", field, valNum))
		vals = append(vals, val)
	}
	sqlStr := fmt.Sprintf("update %s set "+strings.Join(fields, ",")+" where uid = '%s'", s.Name, in.Uid)
	_, err = s.Db.Exec(sqlStr, vals...)
	if err != nil {
		return
	}
	return
}

func (s *Model) GetByUids(uids []string) (ret []*proto.UserUser, err error) {
	args := make([]string, len(uids))
	vals := make([]interface{}, len(uids))
	for k, v := range uids {
		args[k] = fmt.Sprintf("$%d", k+1)
		vals[k] = v
	}
	sqlStr := fmt.Sprintf("select uid, role, discount, platform_discount from %s where uid in ("+strings.Join(args, ",")+")", s.Name)
	rows, err := s.Db.Query(sqlStr, vals...)
	if err != nil {
		return
	}
	defer rows.Close()
	for rows.Next() {
		item := &proto.UserUser{}
		err = rows.Scan(&item.Uid, &item.Role, &item.Discount, &item.PlatformDiscount)
		if err != nil {
			return
		}
		ret = append(ret, item)
	}
	return
}
